package com.ntd.study.pro.zx;

import cn.hutool.core.io.FileUtil;
import com.ntd.study.pro.zx.cbpp.CfgLoader;
import com.ntd.study.pro.zx.cbpp.MsgUtil;
import com.ntd.study.pro.zx.cbpp.SendMsg;
import ntd.util.UtilXml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class UtilZXDf {
    public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
        sendMsg("S0001", "123456484616351351", "62170001351351351", "刘文举", "168");
    }

    /**
     * 发送请求 - 代付
     * @param tranCodeStr
     * @throws UnsupportedEncodingException
     */
    private static void sendMsg(String tranCodeStr, String orderNo, String bankNo, String bankUserName, String price) throws UnsupportedEncodingException {
        CfgLoader.loadCfg();
        String msgfilepath = CfgLoader.properties.getProperty("MSGFILEPATH") + tranCodeStr + ".body";
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("merchantId", "302410148160030");
        bodyMap.put("orderDate", MsgUtil.getMsgDate());
        bodyMap.put("orderTime", MsgUtil.getMsgDateTime());
        bodyMap.put("merSeqId", orderNo);
        bodyMap.put("accType", "01");
        bodyMap.put("accNo", bankNo);
        bodyMap.put("accName", bankUserName);
        bodyMap.put("transAmt", price); // 金额
        bodyMap.put("purpose", "用户抽奖金额提现");
        Document document = buildXml(tranCodeStr, bodyMap);
        UtilXml.writeFile(FileUtil.file(msgfilepath), document, "GBK");
//        IoUtil.write(fileOutputStream, "GBK", true);
        SendMsg.sendMsg(tranCodeStr);
    }

    /**
     * 构造xml文件
     * @param tranCodeStr
     * @param bodyMap
     * @return
     */
    public static Document buildXml(String tranCodeStr, Map<String, String> bodyMap){
        Document doc = UtilXml.createDoc();
        Element request = doc.createElement("request");
        Element tranCode = doc.createElement("tranCode");
        tranCode.setTextContent(tranCodeStr);
        request.appendChild(tranCode);
        Element body = doc.createElement("body");
        bodyMap.entrySet().forEach(stringStringEntry -> {
            Element element = doc.createElement(stringStringEntry.getKey());
            element.setTextContent(stringStringEntry.getValue());
            body.appendChild(element);
        });
        request.appendChild(body);
        doc.appendChild(request);
        return doc;
    }
}
